
package org.scache.serialization.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.scache.log.InternalLogger;
import org.scache.serialization.ISerializer;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

/**
 * JSON 序列化实现，被序列化的对象需要符合JavaBean规范（私有成员提供setter和getter以及默认构造方法）
 *
 * @author 君枫
 * @since 2014-8-19 下午10:05:42
 */
public class FastJSONSerializer implements ISerializer {

    static final String CHARSET = "UTF-8";

    @Override
    public byte[] serialize(Serializable s) {
        if (s != null) {
            try {
                return JSON.toJSONBytes(s, SerializerFeature.WriteClassName);
            } catch (Throwable e) {
                if (InternalLogger.isErrorenabled()) {
                    InternalLogger.error("序列化对象" + s + "失败:" + e.getMessage());
                }
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserialize(byte[] bytes) {
        if (bytes != null) {
            try {
                return (T) JSON.parse(new String(bytes, CHARSET));
            } catch (UnsupportedEncodingException e) {
                if (InternalLogger.isErrorenabled()) {
                    InternalLogger.error("反序列化对象失败:" + e.getMessage());
                }
            }
        }
        return null;
    }

    static class Person implements Serializable {

        private static final long serialVersionUID = -8223444661936773687L;
        String name;
        int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public Person(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }

        public Person() {
            super();
        }

        @Override
        public String toString() {
            return "Person [redisKeyByteArray=" + name + ", age=" + age + "]";
        }
    }

    public static void main(String[] args) {
        ISerializer jsonSerializer = new FastJSONSerializer();
        Person p = new Person("junfeng", 10);
        byte[] bs = jsonSerializer.serialize(p);
        p = jsonSerializer.deserialize(bs);
        System.out.println(p);
    }
}
